package com.cuitrip.business.login;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.app.MainApplication;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.business.login.ui.agreement.AgreementLayout;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.service.R;
import com.cuitrip.storage.prefrence.UserPreferences;
import com.cuitrip.util.text.EmojiFilterUtils;
import com.cuitrip.util.track.TrackUtil;
import com.facebook.appevents.AppEventsConstants;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.network.util.NetworkUtil;
import com.lab.utils.ToastUtil;
import com.lab.utils.Utils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterActivity extends CustomUiFragmentActivity implements View.OnClickListener/*, IProxyCallback*/ {

    @Bind(R.id.ct_refuse_reason)
    TextView ctRefuseReason;

    @Bind(R.id.back_press)
    IconTextView back_press;

    @Bind(R.id.ct_layout_account)
    LinearLayout ctLayoutAccount;

    @Bind(R.id.ct_account)
    EditText ctAccount;

    @Bind(R.id.ct_account_clear)
    IconTextView ct_account_clear;

    @Bind(R.id.ct_layout_email)
    LinearLayout ct_layout_email;

    @Bind(R.id.ct_email)
    EditText ctEmail;

    @Bind(R.id.ct_email_clear)
    IconTextView ct_email_clear;

    @Bind(R.id.ct_layout_passwd)
    LinearLayout ct_layout_passwd;

    @Bind(R.id.ct_passwd)
    EditText ctPasswd;

    @Bind(R.id.ct_passwd_visible)
    IconTextView ctPasswdVisible;

    @Bind(R.id.ct_signup)
    TextView ctSignUp;
    @Bind(R.id.agreement_layout)
    AgreementLayout agreement_layout;

    ApiProxy apiProxy;


    private IProxyCallback registerCallBack = new ApiProxyCallBack() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(Object user, CtApiResponse response) {
            if (response.result instanceof CtUserInfo) {
                CtUserInfo info = (CtUserInfo) response.result;
                LoginInstance.update(RegisterActivity.this, info, true);
            } else {
                LoginInstance.logout(RegisterActivity.this);
                showLoading();
                LoginProxy.getInstance().login(ctEmail.getText().toString(), ctPasswd.getText().toString(), new LoginProxy.CallBack() {
                    @Override
                    public void onLoginSuccess(Object data) {
                        hideLoading();
                        CtUserInfo ctUserInfo = LoginInstance.getInstance().getUserInfo();
                        UserPreferences.getInstance().putString(UserPreferences.UserKeys.LOGIN_PHONE_NUM, ctEmail.getText().toString());
                        finish();
                        if(ctUserInfo == null){
                            ToastUtil.toast(R.string.feedback_sign_in_again);
                        }else{
                            TrackUtil.trackScreenName("/account/set_profile");
                            Intent intent = new Intent(RegisterActivity.this, CompleteUserInfoActivity.class);
                            Jumper.launchActivityForResult(RegisterActivity.this, intent, CompleteUserInfoActivity.REQUEST_COMPLETE_USER);
                        }
                    }

                    @Override
                    public void onLoginFail(int resultCode, String message) {
                        hideLoading();
//                        finish();
                        ToastUtil.toast(R.string.feedback_sign_in_again);
                    }
                });
            }

            MainApplication.getInstance().logger.logEvent(AppEventsConstants.EVENT_NAME_COMPLETED_REGISTRATION);
            return super.onSuccess(user, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                ctRefuseReason.setText(response.msg);
            }
            return super.onFaild(response);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        onCreate(savedInstanceState, R.layout.ct_activity_register);
        ButterKnife.bind(this);
        ctPasswd.setTypeface(Typeface.DEFAULT);
        agreement_layout.changeMode(AgreementLayout.REGISTER_MODE);
        agreement_layout.findViewById(R.id.ct_agree_toggle).setVisibility(View.GONE);
        apiProxy = ApiProxyBuilder.getBuilder().addApiCallBack(ApiManager.REGISTER, registerCallBack).build();
        ctPasswd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                submit();
                return true;
            }
        });
    }

    @Override
    public boolean initCloseTopBar() {
        return true;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        return null;
    }

    @OnClick(R.id.ct_signup)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ct_signup:
                ctRefuseReason.setText("");
                submit();
                break;
        }
    }

    private boolean valid() {
        if (ctAccount.getText() != null) {
            String accountText = EmojiFilterUtils.filterEmoji(ctAccount.getText().toString());
            if (TextUtils.isEmpty(accountText)){
                Utils.shakeView(ctAccount);
                return false;
            }
        }
        if (TextUtils.isEmpty(ctEmail.getText())) {
            Utils.shakeView(ctEmail);
            return false;
        }
        //判断email是否正确
        if (!Utils.isEmail(ctEmail.getText().toString())) {
            Utils.shakeView(ctEmail);
            ctRefuseReason.setText(R.string.mail_limit);
            return false;
        }
        if (TextUtils.isEmpty(ctPasswd.getText())) {
            Utils.shakeView(ctPasswd);
            return false;
        }
        return true;
    }

    private void submit() {
        if (!valid()) {
            return;
        }
        if (NetworkUtil.getConnectState(this) == NetworkUtil.CONNECT_NONE) {
            ToastUtil.toast(R.string.feedback_no_internet_1);
            return;
        }
        showLoading();
        UserBusiness.register(apiProxy, ctEmail.getText().toString(), ctPasswd.getText().toString(), ctAccount.getText().toString());
    }

    @OnClick(R.id.back_press)
    @Override
    public void finish() {
        super.finish();
    }

    @OnClick(R.id.ct_passwd_visible)
    public void changePasswordVisible(View view) {
        view.setSelected(!view.isSelected());
        if (view.isSelected()) {
            ctPasswdVisible.setText(R.string.show_pwd_icon);
            int selectionEnd = ctPasswd.getSelectionEnd();
            ctPasswd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ctPasswd.setSelection(selectionEnd);
        } else {
            ctPasswdVisible.setText(R.string.hide_pwd_icon);
            int selectionEnd = ctPasswd.getSelectionEnd();
            ctPasswd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ctPasswd.setSelection(selectionEnd);
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isHideInput(view, ev)) {
                HideSoftInput(view.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    // 判定是否需要隐藏
    private boolean isHideInput(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] l = { 0, 0 };
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top
                    && ev.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
    // 隐藏软键盘
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
